package pl.myszon.RILLib;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import javax.net.ssl.*;

/**
 *
 * @author Myszon
 */
class HTTPSConnectionHandler {
    Config config;
    URL url;
    HttpsURLConnection httpsConn;

    public HTTPSConnectionHandler(Config conf, String url) throws ConnectionFailureException {
        try {
            config = conf;
            this.url = new URL(url);
            httpsConn = (HttpsURLConnection) this.url.openConnection();
        } catch (MalformedURLException ex) {
            throw new ConnectionFailureException(ex.getMessage());
        } catch (IOException ex) {
            throw new ConnectionFailureException(ex.getMessage());
        }
    }

     String getContent() throws ConnectionFailureException {
        try {
            String contentType = httpsConn.getContentType();
            if(!contentType.contains("text/html"))
                throw new ConnectionFailureException("Invalid content type ("+contentType+")");

            BufferedReader br = new BufferedReader(new InputStreamReader(httpsConn.getInputStream()));
            StringBuilder sb = new StringBuilder(16384);
            try {
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                    sb.append('\n');
                }
            } finally {
                br.close();
            }
            return sb.toString();

        } catch (IOException ex) {
            throw new ConnectionFailureException(ex.getMessage());
        } catch (ClassCastException ex) {
            throw new ConnectionFailureException(ex.getMessage());
        }

    }

    Map getHeader() throws ConnectionFailureException {
        return httpsConn.getHeaderFields();
    }
}
